<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>video</title>
    <style>
        body,
        .container{
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .container{
           display: flex;
            align-items: center;
            justify-content: center;
        }
        .dark{
            background-color: #ff181818;   
        }
    </style>
</head>
<body>
    <div class="container">
        <div>
            <video id="video" width="100%" controls></video>
        </div>
        <div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/hls.js"></script>
    <script>
        function uint8ArrayToString(fileData){
            var dataString = "";
            for (var i = 0; i < fileData.length; i++) {
                dataString += String.fromCharCode(fileData[i]);
            }
            return dataString
        }
        function stringToUint8Array(str){
            var arr = [];
            for (var i = 0, j = str.length; i < j; ++i) {
                arr.push(str.charCodeAt(i));
            }
            return new Uint8Array(arr);
        }
       
        // 初始化完成
        window.addEventListener("flutterInAppWebViewPlatformReady", async (event)=>{
            var uri  = await window.flutter_inappwebview.callHandler('getM3u8DownloadPath');
            var brightness  = await window.flutter_inappwebview.callHandler('brightness');
            document.body.className=brightness;
            if(Hls.isSupported()) {
                var video = document.getElementById('video');
                var hls = new Hls();
                hls.loadSource(uri);
                hls.attachMedia(video);
                hls.on(Hls.Events.KEY_LOADED, async (event, data)=>{
                    const encryptdata = uint8ArrayToString(data.frag.decryptdata.key);
                    // 解密密钥
                    console.log('primary key file data: ' + encryptdata);
                    var decryptdata  = await window.flutter_inappwebview.callHandler('decodeKey', encryptdata);
                    console.log('plain key file data: ' + decryptdata);
                    data.frag.decryptdata.key = stringToUint8Array(decryptdata);
                });
                hls.on(Hls.Events.MANIFEST_PARSED, async () => {
                    // 自动播放
                    // await video.play();
                })
            };
        })
    </script>
</body>
</html>